import { service } from './service'

import { config } from './config'

const { default_headers } = config

const request = (option: any) => {
  const { headersType, headers, ...otherOption } = option
  return service({
    ...otherOption,
    headers: {
      'Content-Type': headersType || default_headers,
      ...headers
    }
  })
}

// 添加带自定义 headers 的请求方法
const requestWithCustomHeaders = (option: any, customHeaders: any = {}) => {
  const { headersType, headers, ...otherOption } = option
  return service({
    ...otherOption,
    headers: {
      'Content-Type': headersType || default_headers,
      ...headers,
      ...customHeaders
    }
  })
}

export default {
  get: async <T = any>(option: any) => {
    const res = await request({ method: 'GET', ...option })
    return res.data as unknown as T
  },
  post: async <T = any>(option: any) => {
    const res = await request({ method: 'POST', ...option })
    return res.data as unknown as T
  },
  postOriginal: async (option: any) => {
    const res = await request({ method: 'POST', ...option })
    return res
  },
  delete: async <T = any>(option: any) => {
    const res = await request({ method: 'DELETE', ...option })
    return res.data as unknown as T
  },
  put: async <T = any>(option: any) => {
    const res = await request({ method: 'PUT', ...option })
    return res.data as unknown as T
  },
  download: async <T = any>(option: any) => {
    const res = await request({ method: 'GET', responseType: 'blob', ...option })
    return res as unknown as Promise<T>
  },
  upload: async <T = any>(option: any) => {
    option.headersType = 'multipart/form-data'
    const res = await request({ method: 'POST', ...option })
    return res as unknown as Promise<T>
  },
  // 新增带自定义 headers 的方法
  withHeaders: {
    get: async <T = any>(option: any, customHeaders: any = {}) => {
      const res = await requestWithCustomHeaders({ method: 'GET', ...option }, customHeaders)
      return res.data as unknown as T
    },
    post: async <T = any>(option: any, customHeaders: any = {}) => {
      const res = await requestWithCustomHeaders({ method: 'POST', ...option }, customHeaders)
      return res.data as unknown as T
    },
    put: async <T = any>(option: any, customHeaders: any = {}) => {
      const res = await requestWithCustomHeaders({ method: 'PUT', ...option }, customHeaders)
      return res.data as unknown as T
    },
    delete: async <T = any>(option: any, customHeaders: any = {}) => {
      const res = await requestWithCustomHeaders({ method: 'DELETE', ...option }, customHeaders)
      return res.data as unknown as T
    }
  }
}
